package com.example.demo;

import java.util.concurrent.TimeUnit;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {

//	public @Bean ClientHttpRequestFactory requestFactory() {
//		OkHttpClient client = new OkHttpClient.Builder()
////				.connectTimeout(10, TimeUnit.SECONDS)
////				.writeTimeout(10, TimeUnit.SECONDS)
////				.readTimeout(30, TimeUnit.SECONDS)
//				.retryOnConnectionFailure(true)
//				.build();
//		return new OkHttp3ClientHttpRequestFactory(client);
//	}

	public @Bean ClientHttpRequestFactory requestFactory() {
		PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(180, TimeUnit.SECONDS);
		cm.setMaxTotal(1000);
		cm.setValidateAfterInactivity(18000);
		cm.setDefaultMaxPerRoute(50);
		HttpClient httpClient=HttpClients.createMinimal(cm);
		HttpComponentsClientHttpRequestFactory requestFactory= new HttpComponentsClientHttpRequestFactory(httpClient);
		requestFactory.setBufferRequestBody(true);
		requestFactory.setConnectionRequestTimeout(2000);
		requestFactory.setConnectTimeout(2000000);
		requestFactory.setReadTimeout(2000);
		return requestFactory;
	}
	@LoadBalanced
	public @Bean RestTemplate restTemplate(ClientHttpRequestFactory requestFactory) {
		RestTemplate restTemplate = new RestTemplate(requestFactory);
//		restTemplate.getInterceptors().add((request, body, execution) -> {
		return restTemplate;
	}


//	public@Bean UndertowDeploymentInfoCustomizer websocketServletWebServerCustomizer() {
//	return deploymentInfo->{
//		WebSocketDeploymentInfo info = new WebSocketDeploymentInfo();
//		info.setBuffers(new DefaultByteBufferPool(true, 1024000));
//		deploymentInfo.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, info);
//	
//	};
//}
}
